package com.sky.websocket;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket  客户端  用于发送信息给客户端浏览器。。。
 */
@ServerEndpoint("/ws/{uuid}")
@Component
@Slf4j
public class WebSocketServer {
    //  每个用户建立的会话对象
    private Session session;
    //  每个用户唯一标识id
    private String uuid;
    //  线程安全Map保存客户端连接
    private static ConcurrentHashMap<String, Session> map = new ConcurrentHashMap();

    @OnOpen
    public void open(Session session, @PathParam("uuid") String uuid) {
        this.session = session;
        this.uuid = uuid;
        map.put(uuid, session);
        log.info("----ws建立客户端链接，uuid：{}--，客户端数量：{}个", uuid, map.size());
    }

    //  接收客户端发送消息
    @OnMessage
    public void accept(String message, Session session) throws IOException {
        log.info(uuid + "ws收到客户端发送消息：{}", message);
    }

    @OnClose
    public void close(@PathParam("uuid") String uuid) {
        log.info("ws断开-关闭资源：{}", uuid);
    }


    //  用户新订单和催单
    public void sendReminder(String message) {
        for (String key : map.keySet()) {
            if (key.startsWith("admin")) {
                //   催单 来单提醒消息回送
                Session session = map.get(key);
                if (session.isOpen()) {
                    try {
                        session.getBasicRemote().sendText(message);
                    } catch (IOException e) {
                        log.error("新订单或催单消息推送失败：{}", e.getMessage(), e);
                    }
                }
            }
        }
    }


    //  发送给指定的客户端  rider_1   rider_2
    public void sendRiderInfo(String message, Long courierId) {
        log.info("推送消息给：{}", courierId + "号骑手");
        for (String key : map.keySet()) {
            if (key.equals("rider_" + courierId)) {
                Session session = map.get(key);
                if (session.isOpen()) {
                    try {
                        session.getBasicRemote().sendText(message);
                    } catch (IOException e) {
                        log.error("指定用户：{}的消息推送失败：{}", courierId, e.getMessage(), e);
                    }
                }
            }
        }
    }

    //  发送消息给所有的客户端
    public void sendAll(String message) {
        for (String key : map.keySet()) {
            Session session = map.get(key);
            if (session.isOpen()) {
                try {
                    session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    log.error("广播消息推送失败：{}", e.getMessage(), e);
                }
            }
        }
    }

    public void notifyCourier(String orderNumber, Long courierId){
        Map<String, Object> map = new HashMap<>();
        map.put("tradeNo", orderNumber);
        map.put("code", 1);
        map.put("msg", "您有新的待接单，请及时查收！");
        String message = JSON.toJSONString(map);
        // 推送消息
        sendRiderInfo(message, courierId);
    }

}